package com.yuan.java.nettydemo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.junit.Test;

/**
 * 简化版 http 协议请求
 *
 * @author yuaneg 2020/1/14
 */
public class HttpServer {

    @Test
    public void run() throws InterruptedException {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpRequestDecoder());
                            ch.pipeline().addLast(new HttpObjectAggregator(78787));
                            ch.pipeline().addLast(new HttpResponseEncoder());
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
                                @Override
                                protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
                                    byte[] req = new byte[msg.content().readableBytes()];
                                    msg.content().readBytes(req);
                                    String body = new String(req, "UTF-8");
                                    System.out.println(body);
                                    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
                                    fullHttpResponse.headers().add("content-type", "text/html;charset=utf-8");
                                    fullHttpResponse.content().writeBytes("你好啊啊啊 啊啊啊啊".getBytes());
                                    //add Listener  close 消息发送后关闭连接 直接放回数据 ,websocket 则不关闭
                                    ctx.writeAndFlush(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
                                }
                            });
                        }
                    });
            serverBootstrap.bind(8080).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

}
